package com.mdd.front.service.salesman.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mdd.common.constant.GlobalConstant;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.goods.Goods;
import com.mdd.common.entity.goods.GoodsSpecification;
import com.mdd.common.entity.salesman.SalesmanGoogs;
import com.mdd.common.entity.salesman.Salesman;
import com.mdd.common.entity.salesman.UserSalesman;
import com.mdd.common.mapper.goods.GoodsMapper;
import com.mdd.common.mapper.salesman.SalesmanMapper;
import com.mdd.common.mapper.salesman.UserSalesmanMapper;
import com.mdd.common.mapper.specification.GoodsSpecificationMapper;
import com.mdd.common.utils.TimeUtil;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.googs.ISalesmanGoogsService;
import com.mdd.front.service.salesman.ISalesmanService;
import com.mdd.front.validate.PageParam;
import com.mdd.front.validate.salesman.SalesmanParam;
import com.mdd.front.vo.goods.GoodsDetailVo;
import com.mdd.front.vo.salesman.SalesmanDetailVo;
import com.mdd.front.vo.salesman.SalesmanListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 推销员实现类
 */
@Service
public class SalesmanServiceImpl extends ServiceImpl<SalesmanMapper, Salesman> implements ISalesmanService {

	@Resource
	private ISalesmanGoogsService salesmanGoogsService;

	@Resource
	private UserSalesmanMapper userSalesmanMapper;

	@Resource
	private GoodsMapper goodsMapper;
	@Resource
	private GoodsSpecificationMapper goodsSpecificationMapper;

	/**
	 * 推销员列表
	 *
	 * @param pageParam 分页参数
	 * @param params    搜索参数
	 * @return PageResult<SalesmanListVo>
	 * @author 蒋海省
	 */
	@Override
	public PageResult<SalesmanListVo> list(PageParam pageParam, Map<String, String> params) {
		Integer page = pageParam.getPageNo();
		Integer limit = pageParam.getPageSize();

		QueryWrapper<Salesman> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("is_delete", 0);
		queryWrapper.orderByDesc("id");

		this.baseMapper.setSearch(queryWrapper, params, new String[]{
				"=:userId@user_id:long",
				"like:name:str",
				"like:mobile:str",
				"=:zone:str",
				"=:discount:long",
		});

		IPage<Salesman> iPage = this.baseMapper.selectPage(new Page<>(page, limit), queryWrapper);

		List<SalesmanListVo> list = new LinkedList<>();
		for (Salesman item : iPage.getRecords()) {
			SalesmanListVo vo = new SalesmanListVo();
			BeanUtils.copyProperties(item, vo);
//            vo.setId(item.getId());
			if (item.getUpdateTime() != null) {
				vo.setUpdateTime(TimeUtil.timestampToDate(Long.valueOf(item.getUpdateTime())));
			}
			vo.setCreateTime(TimeUtil.timestampToDate(Long.valueOf(item.getCreateTime())));
			list.add(vo);
		}

		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
	}

	/**
	 * 推销员详情
	 *
	 * @param id 主键参数
	 * @return Salesman
	 * @author 蒋海省
	 */
	@Override
	public SalesmanDetailVo detail(Integer id) {
		Salesman model = this.baseMapper.selectOne(
				new QueryWrapper<Salesman>()
						.eq("id", id)
						.eq("is_delete", 0)
						.last("limit 1"));

		Assert.notNull(model, "数据不存在");

		SalesmanDetailVo vo = new SalesmanDetailVo();
		BeanUtils.copyProperties(model, vo);
		return vo;
	}

	/**
	 * 推销员新增
	 *
	 * @param salesmanParam 参数
	 * @author 蒋海省
	 */
	@Override
	public void add(SalesmanParam salesmanParam) {
		Salesman model = new Salesman();
		model.setUserId(salesmanParam.getUserId());
		model.setName(salesmanParam.getName());
		model.setMobile(salesmanParam.getMobile());
		model.setZone(salesmanParam.getZone());
		model.setDiscount(salesmanParam.getDiscount());
		model.setStatus(salesmanParam.getStatus());
		model.setCreateTime(Math.toIntExact(System.currentTimeMillis() / 1000));
		this.baseMapper.insert(model);
	}

	/**
	 * 推销员编辑
	 *
	 * @param salesmanParam 参数
	 * @author 蒋海省
	 */
	@Override
	public void edit(SalesmanParam salesmanParam) {
		Salesman model = this.baseMapper.selectOne(
				new QueryWrapper<Salesman>()
						.eq("id", salesmanParam.getId())
						.eq("is_delete", 0)
						.last("limit 1"));

		Assert.notNull(model, "数据不存在!");

		model.setId(salesmanParam.getId());
		model.setUserId(salesmanParam.getUserId());
		model.setName(salesmanParam.getName());
		model.setMobile(salesmanParam.getMobile());
		model.setZone(salesmanParam.getZone());
		model.setDiscount(salesmanParam.getDiscount());
		model.setStatus(salesmanParam.getStatus());
		model.setUpdateTime(Math.toIntExact(System.currentTimeMillis() / 1000));
		this.baseMapper.updateById(model);
	}

	/**
	 * 推销员删除
	 *
	 * @param id 主键ID
	 * @author 蒋海省
	 */
	@Override
	public void del(Integer id) {
		Salesman model = this.baseMapper.selectOne(
				new QueryWrapper<Salesman>()
						.eq("id", id)
						.eq("is_delete", 0)
						.last("limit 1"));

		Assert.notNull(model, "数据不存在!");

		model.setIsDelete(1);
		model.setDeleteTime((int) (System.currentTimeMillis() / 1000));
		this.baseMapper.updateById(model);
	}

	@Override
	public GoodsDetailVo getGoodsDetailForSalesman(Integer id) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		UserSalesman userSalesman = userSalesmanMapper.selectOne(new LambdaQueryWrapper<UserSalesman>()
				.eq(UserSalesman::getUserId, userId)
				.eq(UserSalesman::getIsDelete, GlobalConstant.NOT_DELETE));
		Goods goods = goodsMapper.selectOne(new LambdaQueryWrapper<Goods>());
		GoodsDetailVo target = new GoodsDetailVo();
		BeanUtils.copyProperties(goods, target);
		if (Objects.isNull(userSalesman)) {
			return target;
		}

		LambdaQueryWrapper<SalesmanGoogs> salesmanGoogsLambdaQueryWrapper = new LambdaQueryWrapper<>();
		salesmanGoogsLambdaQueryWrapper.eq(SalesmanGoogs::getProductId, id);
		Integer salesmanId = userSalesman.getSalesmanId();
		Map<Long, BigDecimal> collect = salesmanGoogsService.list(salesmanGoogsLambdaQueryWrapper).stream().collect(Collectors.toMap(SalesmanGoogs::getSalesmanId, SalesmanGoogs::getProductPrice));
		if (collect.containsKey(salesmanId)) {
			target.setPrice(collect.get(salesmanId));
		}
		return target;
	}

	public Goods getGoodsForSalesman(Integer id, Integer isBuy) {
		Integer userId = LikeFrontThreadLocal.getUserId();
		UserSalesman userSalesman = userSalesmanMapper.selectOne(new LambdaQueryWrapper<UserSalesman>()
				.eq(UserSalesman::getUserId, userId)
				.eq(UserSalesman::getIsDelete, GlobalConstant.NOT_DELETE));
		// 获取服务规格信息
		GoodsSpecification goodsSpecification = goodsSpecificationMapper.selectById(id);
		// 获取服务价格进行替换
		Goods goods = goodsMapper.selectOne(new LambdaQueryWrapper<Goods>()
				.eq(Goods::getId, goodsSpecification.getGoodsId())
				.eq(Goods::getIsDelete, GlobalConstant.NOT_DELETE));
		if (Objects.isNull(goods)) {
			return null;
		}
		if (Objects.nonNull(goodsSpecification.getPrice())){
			goods.setPrice(goodsSpecification.getPrice());
			if (Objects.nonNull(goodsSpecification.getBuyNumber()) && isBuy == GlobalConstant.DELETE){
				goods.setPrice(goodsSpecification.getBuyNumber());
			}
		}

		LambdaQueryWrapper<SalesmanGoogs> salesmanGoogsLambdaQueryWrapper = new LambdaQueryWrapper<>();
		salesmanGoogsLambdaQueryWrapper.eq(SalesmanGoogs::getProductId, id);
		if(Objects.nonNull(userSalesman)){
			Integer salesmanId = userSalesman.getSalesmanId();
			Map<Long, BigDecimal> collect = salesmanGoogsService.list(salesmanGoogsLambdaQueryWrapper).stream().collect(Collectors.toMap(SalesmanGoogs::getSalesmanId, SalesmanGoogs::getProductPrice));
			if (collect.containsKey(salesmanId)) {
				goods.setPrice(collect.get(salesmanId));
			}
		}
		return goods;
	}
}
